Making a comparison operator virtual
implies that you want to compare objects of different types by overriding
operator==
, for instance, in a subclass to compare instances of the base class with instances of the subclass. But polymorphic comparison
operators are very difficult to get right, and are actually questionable in concept. After all, can two objects with only a few common members really
be equal?
This rule raises issues on virtual
comparison operators.
Noncompliant code example
struct Foo {
virtual bool operator==(const Foo &other) const; // Noncompliant
virtual bool operator!=(const Foo &other) const; // Noncompliant
};
Compliant solution
struct Foo {
bool operator==(const Foo &other) const;
bool operator!=(const Foo &other) const;
};